package com.tlkg.qa.redistest.tian;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.concurrent.locks.ReentrantLock;

import org.apache.commons.lang.StringUtils;

import redis.clients.jedis.Jedis;
import redis.clients.jedis.JedisPool;
import redis.clients.jedis.JedisPoolConfig;
import redis.clients.jedis.Transaction;

//import com.audiocn.publicutil.ExceptionUtil;
//import com.audiocn.publicutil.SystemUtil;
//import com.audiocn.util.SerializeUtil;
//import com.audiocn.util.sendmail.MailUtil;

public class RedisUtil {
    
    private static JedisPool jedisPool;

    // 连接池配置信息
    private static JedisPoolConfig redisConfig;
    // 可用的Redis服务器
    private static  List<RedisServer> redisServers;
    // 尝试次数
    private static int retries = 3;

    // 已经尝试的次数
    private static int retriesNum = 0;

    // 使用的配置索引
    private static int serverIndex = 0;
    
    //尝试切换Redies服务多少次了
    private static int tryReconnectionTime = 0;

    private static ReentrantLock lock = new ReentrantLock();


    private static void init(){
        if(redisServers == null || redisServers.size()==0){
            throw new IllegalStateException("没有可用的redisServer");
        }

        jedisPool = crateJedisPool(redisServers.get(serverIndex));
    }
    
    /**
     * 释放jedis资源
     * @param jedis
     */
    public static void returnResource(final Jedis jedis) {
        try{
            if(jedis != null) {
                jedisPool.returnResource(jedis);
            }
        }catch (Exception e) {
            e.printStackTrace();
            jedisPool.returnBrokenResource(jedis);
        }
    }

    /**
     * 创建Redis连接车
     * @param redisServer
     * @return
     */
    private static JedisPool crateJedisPool(RedisServer redisServer){
        try {
            return new JedisPool(redisConfig, redisServer.getHost(), redisServer.getPort(), redisServer.getTimeOut());
        } catch(Exception e) {
            System.out.println("创建连接池异常：");
            e.printStackTrace();
        }
        return null;
    }

    /**
     * 获取Jedis实例<br>
     * 如果用了此方法，必须用完后手动关闭连接
     * @return
     */
    public static Jedis getJedis() {
        try {
            Jedis jedis = jedisPool.getResource();
            //只要成功就把尝试次数更改为0
            if(tryReconnectionTime != 0){
                try{
                    int times = tryReconnectionTime;
                    tryReconnectionTime = 0;
                    RedisServer redisServer = redisServers.get(serverIndex);
                    
//                    //发切换邮件
//                    StringBuffer emailContent = new StringBuffer();
//                    emailContent.append("当前连接服务服务："+redisServer.getHost()+":"+redisServer.getPort()+"<br>");
//                    emailContent.append("重连次数："+times+"<br>");
//                    emailContent.append(SystemUtil.getServerBaseInfoHtml(RedisUtil.class));
//                    
//                    //发连接成功邮件
//                    MailUtil.SendMail(
//                        new String[]{"server.list@tlkg.com","servicede.list@tlkg.com"},
//                        "OK Redis连接成功！"+System.currentTimeMillis(),
//                        emailContent.toString()
//                    );
                }catch(Exception e){
                    e.printStackTrace();
                }
            }
            return jedis;
        } catch (Exception e) {
            e.printStackTrace();
            try {
                // 多线程调用，加锁
                lock.lock();
                retriesNum++;
                // 尝试指定次数获得连接，如果仍然活动不到则创建新的redis连接池
                if(jedisPool != null && retriesNum < retries){
                    return getJedis();
                } else {
                    try{
                        Jedis jedis = jedisPool.getResource();
                        return jedis;
                    }catch(Exception ee){
                        ee.printStackTrace();
                    }
                    
                    RedisServer aldRedisServer = redisServers.get(serverIndex);
                    serverIndex = (++serverIndex)%redisServers.size();
                    jedisPool.destroy();    // 释放原来失败的连接池
                    RedisServer newRedisServer = redisServers.get(serverIndex);
                    jedisPool = crateJedisPool(newRedisServer);
                    retriesNum = 0;
                    
                    //切换次数加1
                    tryReconnectionTime++;
                    if(tryReconnectionTime > redisServers.size()*2){
                        return null;
                    }
                    
//                    //发切换邮件
//                    StringBuffer emailContent = new StringBuffer();
//                    emailContent.append("失败服务："+aldRedisServer.getHost()+":"+aldRedisServer.getPort()+"<br>");
//                    emailContent.append("新服务："+newRedisServer.getHost()+":"+newRedisServer.getPort()+"<br>");
//                    emailContent.append("重连次数："+tryReconnectionTime+"<br>");
//                    emailContent.append(SystemUtil.getServerBaseInfoHtml(RedisUtil.class));
//                    
//                    //发重连邮件
//                    MailUtil.SendMail(
//                        new String[]{"server.list@tlkg.com","servicede.list@tlkg.com"},
//                        "Err Redis连接失败！"+System.currentTimeMillis(),
//                        emailContent.toString()+"<br>"+ExceptionUtil.getHtmlStackTrace(e, "")
//                    );
                    
                    return getJedis();
                }
            } finally{
                lock.unlock();
            }
        }

    }

    /**
     * 添加value
     * @param key
     * @param value
     * @return
     */
    public static Long sadd(String key , String value){
        Jedis jedis=getJedis();
        try {
            return jedis.sadd(key, value);  
        } catch(Exception ex) {
            ex.printStackTrace();
            return 0L;
        } finally {
            returnResource(jedis);
        }
    }
    /**
     * 删除value
     * @param key
     * @param value
     * @return
     */
    public static Long srem(String key , String value){
        Jedis jedis=getJedis();
        try {
            return jedis.srem(key, value);
        } catch(Exception ex) {
            ex.printStackTrace();
            return 0L;
        } finally {
            returnResource(jedis);
        }
    }
    /**
     * 获取所有加入的value  
     * @param key
     * @return
     */
    public static Set<String> smembers(String key){
        Jedis jedis=getJedis();
        try {
            return jedis.smembers(key);
        } catch(Exception ex) {
            ex.printStackTrace();
            return new HashSet<String>();
        } finally {
            returnResource(jedis);
        }
    }

    /**
     * 获取缓存
     * @return
     */
    public static String get(String name) {
        Jedis jedis=getJedis();
        try {
            return jedis.get(name);
        } catch(Exception ex) {
            System.out.println(ex.getMessage());
            //ex.printStackTrace();
            return null;
        } finally {
            returnResource(jedis);
        }
    }
    /**
     * 获取缓存
     * @return
     */
    public static Set<String> getKeys(String prefix) {
        Jedis jedis=getJedis();
        try {
            return jedis.keys(prefix+"*");
        } catch(Exception ex) {
            ex.printStackTrace();
            return new HashSet<String>();
        } finally {
            returnResource(jedis);
        }
    }

    /**
     * 从一个map中获取数据
     * @param key
     * @param field
     * @return
     */
    public static String hGet(String key, String field) {
        Jedis jedis=getJedis();
        try {
            return jedis.hget(key, field);
        } catch(Exception ex) {
            ex.printStackTrace();
            return null;
        } finally {
            returnResource(jedis);
        }
    }

    /**
     * 获取一个map的所有数据
     * @param key
     * @param field
     * @return
     */
    public static Map<String, String> hGetAll(String key) {
        Jedis jedis=getJedis();
        try {
            return jedis.hgetAll(key);
        } catch(Exception ex) {
            ex.printStackTrace();
            return new HashMap<String, String>();
        } finally {
            returnResource(jedis);
        }
    }

    /**
     * 获取一个map的所有数据
     * @param key
     * @return
     */
    public static Map<Object, Object> hGetObjectAll(String key) {
        Jedis jedis=getJedis();
        Map<Object, Object> objectMap = new HashMap<Object, Object>();
        try {
            Map<byte[], byte[]> byteMap = jedis.hgetAll(key.getBytes());
            if(byteMap!=null){
                for (Map.Entry<byte[], byte[]> entry : byteMap.entrySet()){
                    objectMap.put(SerializeUtil.unserialize(entry.getKey()),SerializeUtil.unserialize(entry.getValue()));
                }
            }
        } catch(Exception ex) {
            ex.printStackTrace();
        } finally {
            returnResource(jedis);
        }
        return objectMap;
    }

    /**
     * 从一个map中获取数据
     * @param key
     * @param field
     * @return
     */
    public static Object hGetObject(String key, String field) {
        Jedis jedis=getJedis();
        try {
            byte[] objByte=jedis.hget(key.getBytes(), field.getBytes());
            return SerializeUtil.unserialize(objByte);
        } catch(Exception ex) {
            ex.printStackTrace();
            return null;
        } finally {
            returnResource(jedis);
        }
    }

    /**
     * 向一个map中存放数据
     * @param key
     * @param field
     * @param value
     * @return
     */
    public static String hSet(String key, String field, String value) {
        if(StringUtils.isEmpty(key) || StringUtils.isEmpty(field) || StringUtils.isEmpty(value)){
            return value;
        }
        Jedis jedis=getJedis();
        try {
            jedis.hset(key, field, value);
            return value;
        } catch(Exception ex) {
            ex.printStackTrace();
            return value;
        } finally {
            returnResource(jedis);
        }
    }

    /**
     * 向一个map中存放数据
     * @param key
     * @param field
     * @param value
     * @return
     */
    public static Object hSetObject(String key, String field, Object value) {
        if(StringUtils.isEmpty(key) || StringUtils.isEmpty(field) || null == value){
            return value;
        }
        Jedis jedis=getJedis();
        try {
            jedis.hset(key.getBytes(), field.getBytes(), SerializeUtil.serialize(value));
            return value;
        } catch(Exception ex) {
            System.out.println("RedisUtil.hSetObject find null<key:" + key + "><field:" + field + "><value:" + value + ">");
            ex.printStackTrace();
            return value;
        } finally {
            returnResource(jedis);
        }
    }
    
    /**
     * 向一个map中存放数据
     * @param key
     * @param field
     * @param value
     * @return
     */
    public static Long hDelObject(String key, String field) {
        if(StringUtils.isEmpty(key) || StringUtils.isEmpty(field)){
            return 0L;
        }
        Jedis jedis=getJedis();
        try {
            return jedis.hdel(key.getBytes(), field.getBytes());
        } catch(Exception ex) {
            System.out.println("RedisUtil.hDelObject.err <key:" + key + "><field:" + field +">");
            ex.printStackTrace();
            return 0L;
        } finally {
            returnResource(jedis);
        }
    }

    /**
     * 查看哈希表 key中，给定域 field是否存在
     * @param key
     * @param field
     * @return
     */
    public static boolean hExists(String key, String field) {
        Jedis jedis=getJedis();
        try {
            return jedis.hexists(key, field);
        } catch(Exception ex) {
            ex.printStackTrace();
            return false;
        } finally {
            returnResource(jedis);
        }
    }
    
    /**
     * 同时将多个 field-value (域-值)对设置到哈希表 key中。会覆盖哈希表中已存在的域。
     * @param key
     * @param map
     */
    public static boolean hmset(String key, Map<String, String> map) {
        Jedis jedis=getJedis();
        try {
        	jedis.hmset(key, map);
        	return true;
        } catch(Exception ex) {
            ex.printStackTrace();
            return false;
        } finally {
            returnResource(jedis);
        }
    }
    
    /**
     * 从redis获取Object
     * @param key
     * @return
     */
    public static Object getObject(String key) {
        Jedis jedis=getJedis();
        Object obj=null;
        try {
            byte[] objByte=jedis.get(key.getBytes());
            obj=SerializeUtil.unserialize(objByte);
        } catch(Exception ex) {
            ex.printStackTrace();
            return obj;
        } finally {
            returnResource(jedis);
        }

        return obj;
    }

    /**
     * 设置缓存
     * @return
     */
    public static String set(String key, String value) {
        Jedis jedis=getJedis();
        try {
            jedis.set(key, value);
            return value;
        } catch(Exception ex) {
            System.out.println(ex.getMessage());
            ex.printStackTrace();
            return value;
        } finally {
            returnResource(jedis);
        }
    }

    /**
     * 带有超时时间的redis存储
     * @param key
     * @param time时间(秒)
     * @param value
     * @return
     */
    public static String setWithExpireTime(String key, Integer time, String value) {
        Jedis jedis=getJedis();
        try {
            jedis.setex(key, time, value);
            return value;
        } catch(Exception ex) {
            ex.printStackTrace();
            return value;
        } finally {
            returnResource(jedis);
        }
    }
    
    /**
     * 带有超时时间的redis存储
     * @param key
     * @param time时间(秒)
     * @param value
     * @return
     */
    public static void setWithExpireTime(String key, Integer time, Object object) {
        Jedis jedis=getJedis();
        try {
            jedis.setex(key.getBytes(), time, SerializeUtil.serialize(object));
        } catch(Exception ex) {
            ex.printStackTrace();
        } finally {
            returnResource(jedis);
        }
    }

    /**
     * 删除缓存
     * @return
     */
    public static Long del(String key) {
        Jedis jedis=getJedis();
        try {
            return jedis.del(key);
        } catch(Exception ex) {
            System.out.println(ex.getMessage());
            //ex.printStackTrace();
        } finally {
            returnResource(jedis);
        }
        return 0L;
    }
    /**
     * 删除缓存
     * @return
     */
    public static void hDel(String key , String field) {
        Jedis jedis=getJedis();
        try {
            jedis.hdel(key, field);
        } catch(Exception ex) {
            ex.printStackTrace();
        } finally {
            returnResource(jedis);
        }
    }
    /**
     * 获取列表
     * @return
     */
   public static List<String> hvals(String key) {
        Jedis jedis=getJedis();
        try {
            return jedis.hvals(key);
        } catch(Exception ex) {
            ex.printStackTrace();
            return new ArrayList<String>();
        } finally {
            returnResource(jedis);
        }
    }
    /**
     * key是否存在
     * @return
     */
    public static boolean exists(String key) {
        Jedis jedis=getJedis();
        try {
            return jedis.exists(key);
        } catch(Exception ex) {
            ex.printStackTrace();
            return false;
        } finally {
            returnResource(jedis);
        }
    }

    /**
     * 删除缓存
     * @return
     */
    public static Long delObject(String key) {
        Jedis jedis=getJedis();
        try {
            return jedis.del(key.getBytes());
        } catch(Exception ex) {
            ex.printStackTrace();
            return 0L;
        } finally {
            returnResource(jedis);
        }
    }

    /**
     * redis存放object
     * @param key
     * @param obj
     * @return
     */
    public static Object setObject(String key, Object obj) {
        Jedis jedis=getJedis();
        try {
            jedis.set(key.getBytes(), SerializeUtil.serialize(obj));
        } catch(Exception ex) {
            ex.printStackTrace();
            return obj;
        } finally {
            returnResource(jedis);
        }
        return obj;
    }
    
    /**
     * 向排序序列中加入一条记录
     * @param key  序列key
     * @param score 得分
     * @param member 元素名称
     */
    public static void zadd(String key, double score, String member) {
        Jedis jedis=getJedis();
        try{
            jedis.zadd(key, score, member);
        }catch(Exception e){
            e.printStackTrace();
        } finally {
            returnResource(jedis);
        }
    }
    /**
     * 向排序序列中加入一条记录
     * @param key  序列key
     * @param score 得分
     * @param member 元素名称
     */
    public static void zadd(String key, long score, String member) {
        Jedis jedis=getJedis();
        try{
            jedis.zadd(key, score, member);
        }catch(Exception e){
            e.printStackTrace();
        } finally {
            returnResource(jedis);
        }
    }
    
    /**
     * 向排序序列中加入一组记录
     * @param key  序列key
     * @param score 得分
     * @param member 元素名称数组
     */
    public static void zaddList(String key, double score, String[] member) {
        Jedis jedis=getJedis();
        try{
            for(int i = 0 ; i < member.length ; i++){
                jedis.zadd(key, score, member[i]);
            }
        }catch(Exception e){
            e.printStackTrace();
        } finally {
            returnResource(jedis);
        }
    }
    
    /**
     * 获取排序序列的总记录数
     * @param key  序列key
     */
    public static long zcard(String key) {
        Jedis jedis=getJedis();
        try{
            return jedis.zcard(key);
        }catch(Exception e){
            e.printStackTrace();
        } finally {
            returnResource(jedis);
        }
        return 0;
    }
    
    /**
     * 获取一个元素在某序列中的得分
     * @param key
     * @param member
     * @return
     */
    public static Double zscore(String key, String member,Double errBack){
        Jedis jedis=getJedis();
        try{
            return jedis.zscore(key, member);
        }catch(Exception e){
            e.printStackTrace();
            return errBack;
        } finally {
            returnResource(jedis);
        }
    }
    
    /**
     * 向排序序列的一条记录上增加得分
     * @param key  序列key
     * @param score 增加的分数
     * @param member 元素名称
     */
    public static void zincrby(String key, double score, String member) {
        Jedis jedis=getJedis();
        try{
            jedis.zincrby(key, score, member);
        }catch(Exception e){
            e.printStackTrace();
        } finally {
            returnResource(jedis);
        }
    }
    
    /**
     * 获取一个元素在某序列中的名次，从小到大排名
     * @param key
     * @param member
     * @return
     */
    public static long zrank(String key, String member){
        Jedis jedis=getJedis();
        try{
            return jedis.zrank(key, member);
        }catch(Exception e){
            e.printStackTrace();
        } finally {
            returnResource(jedis);
        }
        return 0;
    }
    
    /**
     * 从一个序列中获取指定数据。从小到大顺序获取
     * @param key
     * @param start 开始位置
     * @param end 结束位置
     * @return
     */
    public static Set<String> zrange(String key, Long start, Long end){
        Jedis jedis=getJedis();
        try{
            return jedis.zrange(key, start , end);
        }catch(Exception e){
            e.printStackTrace();
        } finally {
            returnResource(jedis);
        }
        return new HashSet<String>();
    }
    
    /**
     * 获取一个元素在某序列中的名次，从大到小排名
     * @param key
     * @param member
     * @return
     */
    public static long zrevrank(String key, String member){
        Jedis jedis=getJedis();
        try{
            return jedis.zrevrank(key, member);
        }catch(Exception e){
            e.printStackTrace();
        } finally {
            returnResource(jedis);
        }
        return 0;
    }
    
    /**
     * 从一个序列中获取指定数据。从大到小顺序获取
     * @param key
     * @param start 开始位置
     * @param end 结束位置
     * @return
     */
    public static Set<String> zrevrange(String key, Long start, Long end){
        Jedis jedis=getJedis();
        try{
            return jedis.zrevrange(key, start , end);
        }catch(Exception e){
            e.printStackTrace();
        } finally {
            returnResource(jedis);
        }
        return new HashSet<String>();
    }
    
    /**
     * 集合运算，把几个集合的数据合并到一个集合中
     * @param toKey合并的目的地集合
     * @param fromKey 从那些集合中合并
     * @return
     */
    public static Long zunionstore(String toKey , String...fromKey){
        Jedis jedis=getJedis();
        try{
            return jedis.zunionstore(toKey,fromKey);
        }catch(Exception e){
            e.printStackTrace();
        } finally {
            returnResource(jedis);
        }
        return 0L;
    }
    
    /**
     * 返回指定key的类型
     * @param key
     * @return
     */
    public static String type(String key){
        Jedis jedis=getJedis();
        try{
            return jedis.type(key);
        }catch(Exception e){
            e.printStackTrace();
        } finally {
            returnResource(jedis);
        }
        return null;
    }

    public static void main(String[] args) {
        try {
            RedisUtil.del("rank_user_week_51");
            Set<String> set = RedisUtil.zrevrange("rank_user_week_51", new Long(1), new Long(5));
            System.out.println(set);
        } catch(Exception ex) {
            ex.printStackTrace();
        }
    }

    /**
     * 获取一个元素在某序列中的得分
     * @param key
     * @param member
     * @return
     */
    public static long incr(String key){
        Jedis jedis=getJedis();
        try{
            return jedis.incr(key);
        }catch(Exception e){
            e.printStackTrace();
            jedis.set(key, "0");
        } finally {
            returnResource(jedis);
        }
        return 0;
    }
    
    /**
     * 在list的尾部插入<br>
     * 在redis里插入list的数据类型的数据 (取出当前list所有数据,然后在尾部插入新增数据)
     * @param key
     * @param value
     * @return
     */
    public static void rpush(String key, String value){
        Jedis jedis=getJedis();
        try{
            jedis.rpush(key, value);
        }catch(Exception e){
            e.printStackTrace();
        } finally {
            returnResource(jedis);
        }
    }
	
	/**
     * 在list的尾部插入,保留list中的后边maxlength条数据(只保留最新数据)<br>
     * @param key String
     * @param value Object
     * @param maxLength 只保留list中的后边maxlength条数据
     * @return
     */
    public static void rpushObject(String key, Object value, int maxLength){
    	Jedis jedis=getJedis();
        try{
        	jedis.rpush(key.getBytes(),SerializeUtil.serialize(value));
        	try{
	        	Long max = jedis.llen(key);
	        	int start = max > maxLength?max.intValue()-maxLength:0;
	        	jedis.ltrim(key.getBytes(), start, -1);
        	}catch(Exception e){
        		e.printStackTrace();
        	}
    	}catch(Exception e){
    		e.printStackTrace();
    	} finally {
    		returnResource(jedis);
    	}
    }
    
    /**
     * 在list的尾部插入<br>
     * 在redis里插入list的数据类型的数据 (取出当前list所有数据,然后在尾部插入新增数据)
     * @param key String
     * @param value Object
     * @return
     */
    public static void rpushObject(String key, Object value){
        Jedis jedis=getJedis();
        try{
            jedis.rpush(key.getBytes(),SerializeUtil.serialize(value));
        }catch(Exception e){
            e.printStackTrace();
        } finally {
            returnResource(jedis);
        }
    }
    /**
     * 从redis里获取list的所有数据
     * @param key
     * @param start 开始位置
     * @param end 结束位置 -1 表示获取全部
     * @return 
     * @return
     */
    public static List<String> lrange(String key, int start ,int end){
        Jedis jedis=getJedis();
        try{
            return jedis.lrange(key, start, end);
        }catch(Exception e){
            e.printStackTrace();
        } finally {
            returnResource(jedis);
        }
        return null;
    }
    
    /**
     * 从redis里获取list的所有数据
     * @param key
     * @param start 开始位置
     * @param end 结束位置 -1 表示获取全部
     * @return 
     * @return
     */
    public static List<Object> lrangeObject(String key, int start ,int end){
        Jedis jedis=getJedis();
        try{
            List<Object> listObject = new ArrayList<Object>();
            List<byte[]> list = jedis.lrange(key.getBytes(), start, end);
            for(byte[] b : list){
                listObject.add(SerializeUtil.unserialize(b));
            }
            return listObject;
        }catch(Exception e){
            e.printStackTrace();
        } finally {
            returnResource(jedis);
        }
        return null;
    }
    
    /**
     * 从redis里获取list中的第几条数据
     * @param key
     * @param start 开始位置
     * @param end 结束位置 -1 表示获取全部
     * @return 
     * @return
     */
    public static byte[] lindex(String key, int index){
        Jedis jedis=getJedis();
        try{
            return jedis.lindex(key.getBytes(), index);
        }catch(Exception e){
            e.printStackTrace();
        } finally {
            returnResource(jedis);
        }
        return null;
    }
    /**
     * 从redis里获取list的长度
     * @param key
     * @param start 开始位置
     * @param end 结束位置 -1 表示获取全部
     * @return 
     * @return
     */
    public static Long llen(String key){
        Jedis jedis=getJedis();
        try{
            return jedis.llen(key.getBytes());
        }catch(Exception e){
            e.printStackTrace();
        } finally {
            returnResource(jedis);
        }
        return 0L;
    }
    
    /**
     * 保留key中从start到end的数据，其他删除
     * @param key
     * @param start
     * @param end
     */
    public static void ltrim(String key ,int start ,int end){
        Jedis jedis=getJedis();
        try{
            jedis.ltrim(key, start, end);
        }catch (Exception e) {
            e.printStackTrace();
        } finally {
            returnResource(jedis);
        }
    }
    
    
    /**
     * 从redis中删除某一个对象
     * @param key
     * @param start 开始位置
     * @param end 结束位置 -1 表示获取全部
     * @return 
     * @return
     */
    public static void lrem(String key,String value){
        Jedis jedis=getJedis();
        try{
            jedis.lrem(key, 0, value);
        }catch(Exception e){
            e.printStackTrace();
        } finally {
            returnResource(jedis);
        }
    }
    
    /**
     * 在list的前边插入<br>
     * @param key
     * @param value
     */
    public static void lpush(String key, String value) {
        Jedis jedis=getJedis();
        try{
            jedis.lpush(key,value);
        }catch(Exception e){
            e.printStackTrace();
        } finally {
            returnResource(jedis);
        }       
    }
    
	 /**
     * 在list的前边插入,并保留最前边算起指定的条数(只保留最新数据)<br>
     * @param key String
     * @param value Object
     * @param maxLength 只保留list中的前maxlength条数据
     * @return
     */
	public static void lpushOject(String key, Object value, int maxLength) {
		Jedis jedis=getJedis();
        try{
        	jedis.lpush(key.getBytes(),SerializeUtil.serialize(value));
        	jedis.ltrim(key.getBytes(), 0, maxLength-1);
    	}catch(Exception e){
    		e.printStackTrace();
    	} finally {
    		returnResource(jedis);
    	}
	}
	
    /**
     * 在list的前边插入<br>
     * 在redis里插入list的数据类型的数据 (取出当前list所有数据,然后在头部插入新增数据)
     * @param key String
     * @param value Object
     * @return
     */
    public static void lpushOject(String key, Object value){
        Jedis jedis=getJedis();
        try{
            jedis.lpush(key.getBytes(),SerializeUtil.serialize(value));
        }catch(Exception e){
            e.printStackTrace();
        } finally {
            returnResource(jedis);
        }
    }
    
    /**
     * 设置key的过期时间
     * @param key String
     * @param time int  秒
     * @return
     */
    public static void setExpire(String key, int time){
        Jedis jedis=getJedis();
        try{
            jedis.expire(key,time);
        }catch(Exception e){
            e.printStackTrace();
        } finally {
            returnResource(jedis);
        }
    }
    
    /**
     * 把一个key更改成另外一个key
     * @param oldkey
     * @param newkey
     * @return 失败返回null
     */
    public static String rename(String oldkey, String newkey){
        Jedis jedis=getJedis();
        try{
            jedis.del(newkey);
            String back = jedis.rename(oldkey, newkey).toLowerCase();
            if(!"ok".equals(back)){
                System.out.println("RedisUtil.rename:"+back);
                back = null;
            }
            return back;
        }catch(Exception e){
            System.out.println("RedisUtil.rename.exception:"+oldkey+":"+newkey);
            e.printStackTrace();
        } finally {
            returnResource(jedis);
        }
        return null;
    }
    
    /**
     * 把一个key更改成另外一个key
     * @param oldkey
     * @param newkey
     * @param seconds 多少秒后失效
     * @return 失败返回null
     */
    public static String rename(String oldkey, String newkey, int seconds){
        String backSytr = RedisUtil.rename(oldkey, newkey);
        if(null != backSytr){
            RedisUtil.setExpire(newkey, seconds);
            return backSytr;
        }
        return null;
    }
    /**
     * 在list的尾部插入list<br>
     * 在redis里插入list的数据类型的数据 (取出当前list所有数据,然后在尾部插入新增数据)
     * @param key
     * @param value
     * @return
     */
    public static void rpushOjectList(String key, List<Object> list){
        if(null == list || list.size() == 0){
            return;
        }
        Jedis jedis=getJedis();
        try{
            for(Object object : list){
                if(null != object){
                    jedis.rpush(key.getBytes(),SerializeUtil.serialize(object));
                }
            }
        }catch(Exception e){
            e.printStackTrace();
        } finally {
            returnResource(jedis);
        }
    }

    /**
     * 设置缓存
     * @return
     */
    public static boolean setnx(String key, String value) {
        Jedis jedis=getJedis();
        try {
            return Boolean.valueOf(jedis.setnx(key, value).longValue() == 1L);
        } catch(Exception ex) {
            ex.printStackTrace();
            return false;
        } finally {
            returnResource(jedis);
        }
    }
    
    /**
     * 监视对应key
     * @return
     */
    public static boolean watchExec(Jedis jedis, String dishbnum, String lastmum)
    {
        Transaction tx = jedis.multi();
        tx.set(dishbnum, lastmum);
        List<Object> result = tx.exec();
        if (result == null || result.isEmpty()) {
            jedis.unwatch();
            return false;
        }
        return true;
    }
    
    public static Boolean sismember(String string, String string2)
    {
        Jedis jedis=getJedis();
        try {
            return jedis.sismember(string,string2);
        } catch(Exception ex) {
            ex.printStackTrace();
        } finally {
            returnResource(jedis);
        }
        return null;
    }
    
    public void setRetries(int retries) {
        RedisUtil.retries = retries;
    }

    public void setRedisConfig(JedisPoolConfig redisConfig) {
        RedisUtil.redisConfig = redisConfig;
    }

    public void setRedisServers(List<RedisServer> redisServers) {
        RedisUtil.redisServers = redisServers;
    }


}
